package leetcode

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func isBalanced(root *TreeNode) bool {
	return depth(root) != -1
}

func depth(root *TreeNode) int {
	if root == nil {
		return 0
	}

	l := depth(root.Left)
	if l == -1 {
		return -1
	}

	r := depth(root.Right)
	if r == -1 {
		return -1
	}

	c := l - r
	if c > 1 {
		return -1
	}

	if c >= 0 {
		return l + 1
	}

	if c >= -1 {
		return r + 1
	}
	return -1
}
